﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Traceability
{
    /// <summary>
    /// 
    /// </summary>
    public class TraceabilityAddCommandHandler : IRequestHandler<TraceabilityAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Traceability> traceRepository;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="traceRepository"></param>
        public TraceabilityAddCommandHandler(IBaseRepository<T_Traceability> traceRepository, IMapper mapper)
        {
            this.traceRepository = traceRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(TraceabilityAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            result.Message = "添加成功";
            var info = mapper.Map<T_Traceability>(request);
            var model = traceRepository.GetAll().FirstOrDefault(x => x.Batch == request.Batch);
            if (model != null) 
            {
                result.Code = APIEnum.fail;
                result.Message = "生产批次已存在";
                return await Task.FromResult(result);

            }
            result.Data = await traceRepository.Add(info);

            return await Task.FromResult(result);
        }
    }
}
